<template>
  <a-button type="outline" @click="handleClick">AI 生成题目</a-button>
  <a-drawer :width="340" :visible="visible" @ok="handleOk" @cancel="handleCancel" unmountOnClose>
    <template #title>
      AI 生成题目
    </template>
    <div>
      <a-form
        :model="form"
        label-align="left"
        auto-label-width
        @submit="handleSubmit"
      >
        <a-form-item label="应用 id">
          {{ appId }}
        </a-form-item>
        <a-form-item field="questionNumber" label="题目数量">
          <a-input-number
            :min="0"
            :max="20"
            v-model="form.questionNumber"
            placeholder="请输入题目数量"
          />
        </a-form-item>
        <a-form-item field="optionNumber" label="选项数量">
          <a-input-number
            :min="0"
            :max="6"
            v-model="form.optionNumber"
            placeholder="请输入选项数量"
          />
        </a-form-item>
        <a-form-item>
          <a-space size="small">
            <a-button
              :loading="submitting"
              type="primary"
              html-type="submit"
              style="width: 120px"
            >
              {{ submitting ? "生成中" : "一键生成" }}
            </a-button>
            <a-button
              :loading="sseSubmitting"
              type="primary"
              html-type="submit"
              style="width: 120px"
              @click="handleSSESubmit"
            >
              {{ sseSubmitting ? "生成中" : "实时生成" }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import  API from '@/api';
import { useRouter } from 'vue-router';
import { aiGenerateQuestionUsingPost } from '@/api/questionController';
import message from '@arco-design/web-vue/es/message';


  interface Props {
    appId: string,
    onSuccess?: (result: API.QuestionContentDTO[]) => void,
    onSSESuccess?: (result: API.QuestionContentDTO) => void
    onSSEStart: (eventa:any) => void,
    onSSEClose: (eventa:any) => void
  }
  const  props = withDefaults(defineProps<Props>(), {
    appId: () => {
      return ""
    }
  })

  const router = useRouter()

  const form = reactive({
    questionNumber: 10,
    optionNumber: 2
  })

  const visible = ref(false);

  const handleClick = () => {
    visible.value = true;
  };
  const handleOk = () => {
    visible.value = false;
  };
  const handleCancel = () => {
    visible.value = false;
  }

  // 一键生成ai题目
  const submitting = ref(false)
  const handleSubmit = async () => {
    if(!props.appId) return 
    submitting.value = true
    const res:any = await aiGenerateQuestionUsingPost({
      appId: props.appId as any,
      ...form
    })
    if(res.data.code === 0 && res.data.data.length >0){
      if(props.onSuccess){
        // 将生成的题目数据传递给父组件
        props.onSuccess(res.data.data)
      } else {
        message.success('生产题目成功~')
      }
      handleCancel()
    } else {
      message.error('操作失败:' + res.data.message as string)
    }
    submitting.value = false
  }

  // 实时生成ai题目 SSE返回
  const sseSubmitting = ref(false);
  // const handleSSESubmit =  () => {
  //   message.warning('还在开发中~')
  // }
  const handleSSESubmit = async () => {
    if(!props.appId) return 
    sseSubmitting.value = true
    //这里 手动填写完整的后端地址
    const eventSource = new EventSource(
    // todo 手动填写完整的后端地址
    "http://localhost:8101/api/question/ai_generate/sse" +
      `?appId=${props.appId}&optionNumber=${form.optionNumber}&questionNumber=${form.questionNumber}`
    )
    let first = true
    // 接收消息
    eventSource.onmessage = function (event) {
      console.log(event.data)
      // 开始第一次生成并关闭抽屉
      if(first) {
        props.onSSEStart?.(event)
        handleCancel()
        first = !first
      }
      // 调用父元素方法,把新生成的值传递给父元素
      props.onSSESuccess?.(JSON.parse(event.data))
    }
    // 报错或连接关闭时触发
    eventSource.onerror = function (event) {
      // 正常关闭连接 也会调用onerror 可以通过eventSource判断是否正常关闭
      if(event.eventPhase === EventSource.CLOSED){
        console.log('正常关闭连接')
        eventSource.close()
        props.onSSEClose?.(event)
      } else {
        eventSource.close()
      }
     
      // console.log(event.data)
    }
    // 连接建立时触发
    // eventSource.onopen = function (event) {
    //   console.log('建立连接')
    //   props.onSSEStart?.(event)
    //   handleCancel()
    // }
    sseSubmitting.value = false
  }



</script>